package com.sy.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.constant.MessageConstant;
import com.sy.constant.StatusConstant;
import com.sy.dto.UserLoginDTO;
import com.sy.dto.UserLoginDTO02;
import com.sy.mapper.UserMapper;
import com.sy.pojo.Employee;
import com.sy.pojo.User;
import com.sy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 用户端-登录功能
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        //1.根据手机号查询用户
        queryWrapper.eq(User::getPhone,userLoginDTO.getPhone());
        User user = this.getOne(queryWrapper);
        if(user==null){
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //2.前台获取到的密码进行加密
        String password =
                DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        //密码比对
        if(!password.equals(user.getPassword())){
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }
        //3.判断账号是否被锁定
        if(user.getStatus() == StatusConstant.DISABLE){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOCKED);
        }
        //4.判断当前帐户是否被注销
        if (user.getIsDelete() ==StatusConstant.DISABLE){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOG_OFF);
        }
        return user;
    }

    /**
     * 用户端-登录功能(手机号+验证码)
     * @param userLoginDTO02
     * @return
     */
    @Override
    public User login02(UserLoginDTO02 userLoginDTO02) {
        //根据手机号查询用户信息
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,userLoginDTO02.getPhone());
        User user = this.getOne(queryWrapper);
        //判断user是否为null
        if(user==null){
            //该手机号尚未注册 ，直接注册
            //throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
            user = new User();
            user.setName("旺财");
            user.setPhone(userLoginDTO02.getPhone());
            //实现保存操作
            this.save(user);
        }
        //判断手机号是否被禁用或者锁定
        if(user.getStatus() == StatusConstant.DISABLE){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOCKED);
        }
        //判断当前用户是否注销
        if(user.getIsDelete() ==StatusConstant.DISABLE){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOG_OFF);
        }
        return user;
    }
}
